#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import re

from common.logger import Logger

log = Logger().get_logger("gaussdbt_plugin.log")


class GaussDBTUtils:
    # IPV4地址正则表达式预编译
    IPV4_PATTERN = re.compile(r'^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$')

    @staticmethod
    def validate_ipv4(ip_str):
        """
        校验给定字符串是否为IPV4。如果不是，则返回空字符串。

        :param ip_str: 待校验的字符串
        :return: IPV4或空字符串
        """
        if not isinstance(ip_str, str):
            raise ValueError("Input must be a string")

        match = GaussDBTUtils.IPV4_PATTERN.match(ip_str)
        return ip_str if match else ""

    @staticmethod
    def get_value_at_position(arr, position):
        """
        获取数组指定位置的值。
        如果指定位置超出数组范围，则返回空字符串。

        :param arr: 列表或数组
        :param position: 指定的位置（索引）
        :return: 指定位置的值或空字符串
        """
        if 0 <= position < len(arr):
            return arr[position]
        else:
            log.warning(f"Get value at position {position} failed")
            return ""
